package com.wxy.favorites.job;

import com.wxy.favorites.constant.EmailConstants;
import com.wxy.favorites.dto.ClockNoticeDto;
import com.wxy.favorites.entity.Clock;
import com.wxy.favorites.entity.User;
import com.wxy.favorites.service.ClockService;
import com.wxy.favorites.service.UserService;
import com.wxy.favorites.util.EmailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.List;

/**
 * @author wangxiaoyuan
 * 2021/1/25 14:21
 **/
@Component
@Slf4j
public class ClockNoticeJob {

    @Autowired
    private ClockService clockService;

    @Autowired
    private UserService userService;

    @Autowired
    private EmailUtils emailUtils;

    @Scheduled(cron = "${cron.clock-notice-job}")
    @Async
    public void run() throws ParseException {
        try {
            log.info("闹钟通知任务开始执行...");
            // 查询此刻任务
            List<ClockNoticeDto> taskList = clockService.findClockListByNow();
            // 邮件通知
            taskList.forEach(t -> {
                User user = userService.findById(t.getUserId());
                emailUtils.sendHtmlMail(user.getEmail(), EmailConstants.CLOCK_NOTICE_TITLE, t.getContent());
            });
        } catch (Exception e) {
            log.error("闹钟通知任务执行失败", e);
        }
    }
}
